package io.renren.modules.manage.controller;

import io.renren.common.utils.R;
import io.renren.modules.manage.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

/**
 * @Author: linbd
 * @Description:
 * @Date: 2024/4/11 21:00
 */
@Slf4j
@RestController
@RequestMapping("manage/file")
public class UploadController {
    @Value("${uploads.path}")
    private String uploadDir;
    @Autowired
    private UploadService uploadService;
    public static final String SEPARATOR = "/";

    @PostMapping("/upload/{type}")
    //@RequiresPermissions("manage:productcategory:info")
    public R commonUpload(@PathVariable("type") String type, MultipartFile file) {
        if (file.isEmpty()) {
            return R.error("上传的文件为空");
        }

        String fileName = file.getOriginalFilename();
        log.info("上传目录：{}，子目录：{}，文件名：{}", uploadDir, type, fileName);
        String filePath = uploadDir + SEPARATOR + type + SEPARATOR + fileName;

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath);
            Files.write(path, bytes);
            return R.ok("文件上传成功").put("fileInfo", SEPARATOR + type + SEPARATOR + fileName);
        } catch (IOException e) {
            log.error("ERROR", "ERROR", e);
            return R.error("文件上传失败");
        }
    }


    @PostMapping("/delete/{type}")
    public R deleteFile(@PathVariable("type") String type, @RequestBody Map<String, Object> map) {
        return uploadService.deleteFile(uploadDir, type, map.get("filename").toString());
    }


}
